
package com.android.matmanual;


import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BluetoothTest extends BaseActivity {
	public static final int BLUETOOTH_STATE_ENABLED=1;
	public static final int REQUEST_ENABLE_BT = 2;
//	Button closeBt;
//	Button returnBt;
	TextView bluetoothstateTv;
	TextView bluetoothaddressTv;
	TextView bluetoothnameTv;
	LinearLayout bluetoothInfo;
	BluetoothAdapter mBluetoothAdapter;  
	ProgressDialog mLoadingDialog;
	boolean bluetoothIsStart=false;
	WakeLock mWakeLock;
	
	Thread mBluetoothcheck;
	Thread mBluetoothcheck2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitle(getResources().getString(R.string.checkbluetoothtitle));
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, 
    	        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.bluetooth_test);

	   PowerManager pm =
	           (PowerManager) getSystemService(Context.POWER_SERVICE); 
	   mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, 
	          "XYTEST"); 
	   mWakeLock.acquire(); 
		   
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
//		closeBt=(Button)findViewById(R.id.closebt);
//		returnBt=(Button)findViewById(R.id.returnbt);
		bluetoothstateTv=(TextView)findViewById(R.id.bluetoothstate);
		bluetoothaddressTv=(TextView)findViewById(R.id.bluetoothaddress);
		bluetoothnameTv=(TextView)findViewById(R.id.bluetoothname);
		bluetoothInfo=(LinearLayout)findViewById(R.id.bluetoothinfo);
//		closeBt.setOnClickListener(this);
//		returnBt.setOnClickListener(this);	
		
		mBluetoothcheck=new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				while (mBluetoothAdapter.getState()!=BluetoothAdapter.STATE_ON) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				bluetoothHandler.sendEmptyMessageDelayed(BluetoothTest.BLUETOOTH_STATE_ENABLED,1000); 
			}
		});
		
		
		mBluetoothcheck2=new Thread(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				while (mBluetoothAdapter.getState()!=BluetoothAdapter.STATE_OFF) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}				
				mBluetoothAdapter.enable();
				mBluetoothcheck.start();
//				closeBt.setText(getResources().getString(R.string.close));
				bluetoothIsStart=true;
			}
		});
		
		
		
		
		if(mBluetoothAdapter.getState()==BluetoothAdapter.STATE_OFF){
		bluetoothstateTv.setVisibility(View.VISIBLE);
		bluetoothaddressTv.setVisibility(View.VISIBLE);
		bluetoothnameTv.setVisibility(View.VISIBLE);
		bluetoothstateTv.setText(getResources().getString(R.string.checkbluetooth));
		mBluetoothAdapter.enable();
		mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.openbluetooth));
		mBluetoothcheck.start();
//		closeBt.setText(getResources().getString(R.string.close));
		bluetoothIsStart=true;
		}else{
			//Toast.makeText(getApplicationContext(), getResources().getString(R.string.notcheckbluetooth), 1).show();
			mBluetoothAdapter.disable();
			bluetoothstateTv.setVisibility(View.VISIBLE);
			bluetoothaddressTv.setVisibility(View.VISIBLE);
			bluetoothnameTv.setVisibility(View.VISIBLE);
			bluetoothstateTv.setText(getResources().getString(R.string.checkbluetooth));
			mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.openbluetooth));
			mBluetoothcheck2.start();
		}
	}
//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		super.onResume();
//		if(mBluetoothAdapter.getState()==BluetoothAdapter.STATE_ON){
//			bluetoothIsStart=true;
//			closeBt.setText(getResources().getString(R.string.close));
//		}else if(mBluetoothAdapter.getState()==BluetoothAdapter.STATE_OFF){
//			bluetoothIsStart=false;
//			closeBt.setText(getResources().getString(R.string.open));
//		}
//	}
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	if(bluetoothIsStart){ 
			mBluetoothAdapter.disable();
			bluetoothstateTv.setVisibility(View.GONE);
//			closeBt.setText(getResources().getString(R.string.open));
			bluetoothIsStart=false;
    	}
		if(mWakeLock!=null)
		{
			mWakeLock.release(); 
			mWakeLock = null;
		}
		
		if(mLoadingDialog!=null){
			   mLoadingDialog.dismiss();
		}
    }
	public void startDiscovery(){
             if (mBluetoothAdapter.isEnabled())   
             {  
                 mBluetoothAdapter.startDiscovery();  
                 // Create a BroadcastReceiver for ACTION_FOUND   
                 final BroadcastReceiver mReceiver = new BroadcastReceiver()   
                 {  
                     @Override  
                     public void onReceive(Context context, Intent intent)   
                     {  
                         // TODO Auto-generated method stub   
                         String action = intent.getAction();  
                         // When discovery finds a device   
                         if (BluetoothDevice.ACTION_FOUND.equals(action))   
                         {  
                             // Get the BluetoothDevice object from the Intent   
                             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
                             // Add the name and address to an array adapter to show in a ListView   
                             bluetoothaddressTv.setText("bluetooth address:"+device.getAddress());
                             bluetoothnameTv.setText("bluetooth name:"+device.getName());
                         }  
                         
                     }  
                 };  
                 // Register the BroadcastReceiver   
                 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
                 registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy    
             }  

	}
//	public void onClick(View view) {
		// TODO Auto-generated method stub
//		int id=view.getId();
//		switch (id) {
//		case R.id.closebt:
//			if(bluetoothIsStart){ 
//				mBluetoothAdapter.disable();
//				bluetoothstateTv.setVisibility(View.GONE);
//				closeBt.setText(getResources().getString(R.string.open));
//				bluetoothIsStart=false;
//				bluetoothaddressTv.setVisibility(View.GONE);
//				bluetoothnameTv.setVisibility(View.GONE);
//
//			}else{
//				Thread bluetoothcheck=new Thread(new Runnable() {
//					public void run() {
//						// TODO Auto-generated method stub
//						while (mBluetoothAdapter.getState()!=BluetoothAdapter.STATE_ON) {
//							try {
//								Thread.sleep(200);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
//						bluetoothHandler.sendEmptyMessage(BluetoothTest.BLUETOOTH_STATE_ENABLED); 
//					}
//				});
//				if(mBluetoothAdapter.getState()==BluetoothAdapter.STATE_OFF){
//					bluetoothstateTv.setVisibility(View.VISIBLE);
//					bluetoothaddressTv.setVisibility(View.VISIBLE);
//					bluetoothnameTv.setVisibility(View.VISIBLE);
//				bluetoothstateTv.setText(getResources().getString(R.string.checkbluetooth));
//				mBluetoothAdapter.enable();
//				mLoadingDialog = ProgressDialog.show(this, "", getResources().getString(R.string.openbluetooth));
//				bluetoothcheck.start();
//				closeBt.setText(getResources().getString(R.string.close));
//				bluetoothIsStart=true;
//				}else{
//					Toast.makeText(getApplicationContext(), getResources().getString(R.string.notcheckbluetooth), 1).show();
//				}
//			}
//			break;
//		case R.id.returnbt:
//			finish();
//			break;
//		default:
//			break;
//		}
//	}
	Handler bluetoothHandler=new Handler(){
		   public void handleMessage(android.os.Message msg) {
			   if(msg.what==BLUETOOTH_STATE_ENABLED){
				   if(mLoadingDialog!=null){
				   mLoadingDialog.dismiss();
				   }
				   bluetoothstateTv.setText(getResources().getString(R.string.bluetoothisok)+"\n"+getResources().getString(R.string.searchbluetooth));
				   startDiscovery();
			   }
		   }
	   };
	   
		@Override
		protected void onStop() {
			// TODO Auto-generated method stub
	        finish();
			super.onStop();
		}
		
		 @Override
		 public boolean onKeyDown(int keyCode, KeyEvent event) {
	        int result = TestControl.GetKeyEvent(keyCode);
	        if (result != TestControl.DO_NOTHING) {
	        	setResult(result);
	        	finish();
	        }
		 	return true;
		 }
}
		 